const fs = require('fs');
const BaseComponent = require('../../prototype/baseComponent');
const categoryModel = require('../../models/resources/category');

class ResourcesCates extends BaseComponent {
  constructor() {
    super()
  }
  getAll = async (req, res, next) => {
    try {
      let { page = 1, limit = 10 } = req.query
      let list = await categoryModel.find({}, { '__v': 0 }, { lean: true }).skip(Number((page - 1) * limit)).limit(Number(limit))
      let total = await categoryModel.estimatedDocumentCount()
      let data = {
        list: list,
        total: total
      }
      this.sendSuccess(res, data, '查询成功')
    } catch (err) {
      this.sendError(res, err)
    }
  }
  save = async (req, res, next) => {
    try {
      let { name, status, sort } = req.body
      let item = {
        _id: this.createId(),
        name: name,
        status: status,
        sort: sort
      }
      await categoryModel.create(item)
      this.sendSuccess(res, '', '新增成功')
    } catch (err) {
      this.sendError(res, err)
    }
  }
  del = async (req, res, next) => {
    try {
      let { _id = '' } = req.body
      if (!_id) throw new Error("请填写id")
      let details = await categoryModel.findOneAndRemove({ _id: _id })
      if (!details) throw new Error("没有此项，请检查id是否正确")
      this.sendSuccess(res, '', '删除成功')
    } catch (err) {
      this.sendError(res, err)
    }
  }
  update = async (req, res, next) => {
    try {
      let { _id = '' } = req.body
      if (!_id) throw new Error("请项目id")
      console.log(await categoryModel.findOne({ _id: _id }));
      let details = await categoryModel.findOneAndUpdate({ _id: _id }, { $set: req.body })
      if (!details) throw new Error("没有此项目，请检查项目id是否正确")
      this.sendSuccess(res, '', '修改成功')
    } catch (err) {
      this.sendError(res, err)
    }
  }
}
module.exports = new ResourcesCates()